package com.ddyx.common.utils.sms;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.ddyx.common.utils.io.PropertiesUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @ClassName: AliIM.java
 * @Description: aliyun 短信
 * @author: liuhoujie
 * @date: 2018年4月12日
 */
public class AliIM {
	private static ObjectMapper jsonMapper = new ObjectMapper();
	private static String aliTemplateCode = PropertiesUtil.getValue(PropertiesUtil.CONFPATH, "aliTemplateCode");
	private static String aliSignName = PropertiesUtil.getValue(PropertiesUtil.CONFPATH, "aliSignName");
	// private static String title = "DING_CHAT";

	/**
	 * @Description 短信验证码
	 * @return
	 */
	public static boolean shortMessage(String phone, String validateCode) {
		try {
			SendSmsRequest request = new SendSmsRequest();
			request.setSignName(aliSignName);
			Map map = new HashMap<>();
			map.put("code", validateCode);
			String json = jsonMapper.writeValueAsString(map);
			request.setTemplateCode(aliTemplateCode);

			request.setPhoneNumbers(phone);
			request.setTemplateParam(json);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * @Description 数字随机验证码 (默认4位,最大8位)
	 * @return
	 */
	public static String getVerifyCode(Integer bit) {
		String[] sources = { "1", "0", "2", "4", "8", "3", "5", "9", "7", "6" };
		String verifyCode = "";
		if (bit == null && bit < 4 && bit > 8) {
			bit = 4;
		}
		for (int i = 0; i < bit; i++) {
			verifyCode += sources[new Random().nextInt(sources.length)];
		}
		return verifyCode;
	}

	public static void main(String[] args) {
		 shortMessage("13269621006", getVerifyCode(6));
	}
}
